package com.acxy.ants.core.config;

import com.acxy.ants.core.AnnotationBinding;
import com.acxy.ants.core.InitializingBean;
import com.acxy.ants.core.proxy.CGLibProxy;
import com.acxy.ants.core.kit.ScanKit;
import com.acxy.ants.common.kit.StrKit;
import com.acxy.ants.core.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 将@Service 注解的类以键值对存入list
 * 注：只能存入非接口类型对象
 *
 * @author MrShun
 * @version 1.0
 * @Date 2017-05-11
 */
final public class Services {

    private static final Logger logger = LoggerFactory.getLogger(Services.class);

    private static final Map<String, Object> services = new HashMap<>();


    public static Map<String, Object> registerServices(String packages, boolean isDebug) {
        if (services == null || services.size() == 0) {
            List<Class<?>> classesList = (packages == null) ? ScanKit.getAnnotatedClass(Service.class) : ScanKit.getAnnotatedClass(packages, Service.class);
            logger.debug("初始化[service]层 ...");
            List<Class<?>> moduleServiceList = Modules.getModuleServiceList();
            if(moduleServiceList !=null ) classesList.addAll(moduleServiceList);
            for (Class cls : classesList) {
                String clStr = cls.getName();
                String key = StrKit.lastSubstring(clStr, '.', 2).replace(".", "_");
                if (isDebug) logger.debug(">>> {} :: Generator Success !", key);
                try {
                    if(!services.containsKey(key)) {
                        Object object = cls.newInstance();
                        //================== 处理实例化类里面的属性注解信息 ================
                        AnnotationBinding.initFiledValues(object);
                        //采用CGLIB代理实例化service
                        Object proxy = CGLibProxy.createProxy(object);
                        //初始化完成后调用init()实例化
                        if(proxy instanceof InitializingBean){
                            InitializingBean ib = (InitializingBean) proxy;
                            ib.init();
                        }
                        services.put(key, proxy);
                    }
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return services;
    }

    public static Object getService(String key) {
        return services.get(key);
    }
    public static Object setService(String key, Object object){ return services.put(key, object);}
    public static Object getService(Class iclass){
        Object object = null;
        for(Map.Entry<String, Object> entry: services.entrySet()){
            object = entry.getValue();
            if(iclass.isInstance(object)) break;
        }
        return object;
    }
}
